<template>
  <!-- <div class="view-ddl" v-html="sqlData"> </div> -->
  <je-editor-code
    v-model:value="sqlData"
    v-model:language="language"
    height="100%"
    width="100%"
    :readonly="readOnly"
  />
</template>

<script>
  import { defineComponent, reactive, toRefs, onMounted, watch } from 'vue';
  import { createDdlByView } from '@/api/index';
  import { execScript, isPromise, isNotEmpty } from '@jecloud/utils';
  import { useJE } from '@common/helper/je';
  import { Modal, EditorCode } from '@jecloud/ui';
  import { useSourceStore } from '@/store/source-store';
  export default defineComponent({
    name: 'SourceTableDml',
    components: { JeEditorCode: EditorCode },
    props: {
      saveStatus: {
        type: Boolean,
        default: () => false,
      },
    },
    emits: ['saveAction'],
    setup(props, { emit }) {
      const sourceStore = useSourceStore(); //数据源全局状态
      const state = reactive({
        sqlData: '',
        saveAction: false,
        language: 'sql', //编辑器语言
        readOnly: true, //只读状态
      });
      //sql转义
      const sqlTransition = (sql) => {
        let sqlData = '';
        if (isNotEmpty(sql)) {
          const replaceRegex1 = /(\n)/g;
          sqlData = sql.replace(replaceRegex1, '<br/>');
          const replaceRegex2 = /(\t| {2})/g;
          sqlData = sqlData.replace(
            replaceRegex2,
            '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
          );
        }
        return sqlData;
      };
      //执行js语句返回结果
      const execScriptResult = (executeJs) => {
        let flag = true;
        if (isNotEmpty(executeJs)) {
          flag = execScript(executeJs, {
            EventOptions: { isTrusted: true, type: 'dataSource', params: {} },
            JE: useJE(),
          });
          if (isPromise(flag)) {
            return flag;
          } else {
            return flag !== false ? Promise.resolve(flag) : Promise.reject();
          }
        }
      };
      const methods = {
        //加载DML视图
        loadDdl() {
          const curSourceCode = sourceStore.getSourceCode();
          const curSourceData = sourceStore.getSourceDataByCode(curSourceCode);
          const strParamData = {
            queryConfigVo: [],
          };
          //数据配置
          if (curSourceData.DATASOURCE_CONFIG) {
            const queryConfigVo = JSON.parse(curSourceData.DATASOURCE_CONFIG);
            if (queryConfigVo.jsScript) {
              execScriptResult(queryConfigVo.jsScript).then((res) => {
                if (res) {
                  const execObj = {};
                  //存在参数
                  if (res.params) {
                    execObj.params = res.params;
                  }
                  //存在执行条件
                  if (res.querys) {
                    execObj.querys = res.querys;
                  }
                  queryConfigVo.editorFn = execObj;
                } else {
                  queryConfigVo.editorFn = '';
                }
                strParamData.queryConfigVo = queryConfigVo;
              });
            } else {
              strParamData.queryConfigVo = queryConfigVo;
            }
          }
          setTimeout(() => {
            const param = {
              strData: JSON.stringify(strParamData),
              DATASOURCE_TYPE: curSourceData.DATASOURCE_TYPE,
            };
            createDdlByView(param).then((res) => {
              if (res.success) {
                // state.sqlData = sqlTransition(res.data);
                state.sqlData = res.data;
              }
            });
          });
        },
        watchSaveStatus() {
          //监听是否可以进行保存
          const curSourceCode = sourceStore.getSourceCode();
          const curSourceData = sourceStore.getSourceDataByCode(curSourceCode);
          if (curSourceData.DATASOURCE_CONFIG) {
            const queryConfigVo = JSON.parse(curSourceData.DATASOURCE_CONFIG);
            if (queryConfigVo.tableName) {
              state.saveAction = true;
              emit('saveAction', state.saveAction);
              setTimeout(() => {
                state.saveAction = false;
                emit('saveAction', state.saveAction);
              }, 1000);
            } else {
              Modal.alert('请选择资源表', 'warning');
            }
          } else {
            Modal.alert('请选择资源表', 'warning');
          }
        },
      };
      watch(
        () => props.saveStatus,
        (val) => {
          if (val) {
            methods.watchSaveStatus();
          }
        },
      );
      onMounted(() => {
        methods.loadDdl();
      });
      return {
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style scoped lang="less">
  .view-ddl {
    width: 100%;
    height: 100%;
    padding: 15px 19px;
    overflow: auto;
  }
</style>
